<?php
define('IN_MOBILE', true);
require '../../../framework/bootstrap.inc.php';
$_W['siteroot'] = str_replace('addons/junsion_challeng/wisepay/', '', $_W['siteroot']);
$res_code = $_REQUEST['result_code'];
$res_msg = $_REQUEST['result_msg'];
$shopId = $_REQUEST['shopId'];
$money = $_REQUEST['money'];
$yuntype = $_REQUEST['type'];
$orderId = $_REQUEST['orderId'];
$sign = strtoupper($_REQUEST['sign']);
$out_trade_no = $_REQUEST['out_trade_no'];

$sql = 'SELECT * FROM ' . tablename('junsion_challeng_order') . ' WHERE `orderno`=:orderno';
$log = pdo_fetch($sql, array(':orderno'=>$orderId));
$table = 'order';
if(empty($log)){
	$sql = 'SELECT * FROM ' . tablename('junsion_challeng_reward') . ' WHERE `orderno`=:orderno';
	$log = pdo_fetch($sql, array(':orderno'=>$orderId));
	$table = 'reward';
}

file_put_contents(IA_ROOT."/addons/junsion_challeng/wisepay/return".date('Ymd'),"\n data:".json_encode($_REQUEST).' log:'.json_encode($log),FILE_APPEND);
if (empty($log) || $log['price'] != $money){
	file_put_contents(IA_ROOT."/addons/junsion_challeng/wisepay/return".date('Ymd')," feewrong :".$log['price'],FILE_APPEND);
	exit('SUCCESS');
}
$_GPC['i'] = $_W['uniacid'] = $_W['weid'] = $log['weid'];
require IA_ROOT.'/app/common/bootstrap.app.inc.php';
load()->app('common');
load()->app('template');
$cfg = pdo_fetch('select settings from '.tablename('uni_account_modules')." where uniacid='{$_W['uniacid']}' and module='junsion_challeng'");
if (empty($cfg['settings'])) exit('SUCCESS');
$cfg = unserialize($cfg['settings']);
$ps = $cfg['wisepay'];
$key = $ps['appkey'];
$str = "money={$money}&orderId={$orderId}&result_code={$res_code}&shopId={$shopId}&key={$key}";
$msign = strtoupper(md5($str));
if ($msign != $sign){
	file_put_contents(IA_ROOT."/addons/junsion_challeng/wisepay/return".date('Ymd')," signwrong :".$msign,FILE_APPEND);
	exit('SUCCESS');
}
if (empty($log['status']) && $res_code == 'SUCCESS'){//
	//查询订单
	$url = "http://pay.congmingpay.com/pay/query.do?orderId=".$orderId;
	$res = file_get_contents($url);
	$res = json_decode($res,true);
	if ($res['result_code'] == 'FAIL' || !$res['status']){
		file_put_contents(IA_ROOT."/addons/junsion_challeng/wisepay/return".date('Ymd')," reswrong :".json_encode($res),FILE_APPEND);
		exit('SUCCESS');
	}
}
$site = WeUtility::createModuleSite('junsion_challeng');
if(!is_error($site)) {
	$method = 'payResult';
	if (method_exists($site, $method)) {
		$ret = array();
		$ret['weid'] = $log['weid'];
		$ret['uniacid'] = $log['weid'];
		$ret['type'] = 'yun';
		$ret['tag'] = array('transaction_id'=>$out_trade_no);
		$ret['from'] = $log['status'] ? 'return' : 'notify';
		$ret['result'] = strtolower($res_code);
		$ret['tid'] = $log['orderno'];
		$ret['fee'] = $money;
		$ret['table'] = $table;
		$site->$method($ret);
		exit('SUCCESS');
	}
}
exit('fail');